package cn.edu.nit.sys.service.impl;

import cn.edu.nit.sys.dto.StudentDTO;
import cn.edu.nit.sys.entity.Student;
import cn.edu.nit.sys.entity.User;
import cn.edu.nit.sys.mapper.StudentMapper;
import cn.edu.nit.sys.mapper.UserMapper;
import cn.edu.nit.sys.service.StudentService;
import cn.edu.nit.sys.utils.R;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public R getStudentList(Page<StudentDTO> page, String siftName, String deptId, String majorId) {
        JSONObject jsonObject = new JSONObject();
        Page<StudentDTO> studentList = baseMapper.getStudentList(page, siftName, deptId, majorId);
        jsonObject.put("list", studentList.getRecords());
        jsonObject.put("total", studentList.getTotal());
        return R.ok(jsonObject);
    }

    @Override
    @Transactional
    public R removeStudent(String id) {
        int rs = baseMapper.deleteById(id);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", id);
        rs += userMapper.delete(queryWrapper);
        return rs > 1 ? R.ok("删除成功") : R.error("删除失败");
    }
}
